import { memo, useEffect, useRef, useState } from "react";

import { ViewWrapper } from "./style";
import IconArrowLeft from "../../asset/svgs/icon_arrow_left";
import IconArrowRight from "../../asset/svgs/icon_arrow_right";

export const ScrollView = memo(
    (props) => {
        
        const [showRight, setShowRight] = useState(false);
        const [showLeft, setShowLeft] = useState(false);
        const [index, setIndex] = useState(0);
        const totalDistance = useRef();
        const contentRef = useRef();
        useEffect(() => {
            const clientWidth = contentRef.current.clientWidth;
            const scrollWidth = contentRef.current.scrollWidth;
            totalDistance.current = scrollWidth - clientWidth;
            console.log(totalDistance.current);
            setShowRight(totalDistance.current > 0);
        }, [props.children])
        
        const controlClick = (isRight) => {
            console.log("index", index);
            const newIndex = isRight ? index + 1 : index - 1;
            const children = contentRef.current.children;

            // 处理越界情况
            if (newIndex < 0 || newIndex >= children.length) {
                return;
            }

            const el = children[newIndex];
            const newOffset = el.offsetLeft;

            contentRef.current.style.transform = `translate(-${newOffset}px)`;
            setIndex(newIndex);

            // 更新显示状态
            setShowRight(totalDistance.current > newOffset);
            setShowLeft(newOffset >8);

            console.log("newoffset", newOffset);
        };

        return (
            <ViewWrapper>
               
                    {showLeft&&<div className="leftbtn" onClick={()=>controlClick(false)}><IconArrowLeft></IconArrowLeft></div>}
                    {showRight&&<div className="rightbtn" onClick={()=>controlClick(true)}><IconArrowRight></IconArrowRight></div>}
                 
                <div className="scroll-content" ref={contentRef}>
                     {props.children}
                </div>
           </ViewWrapper>
        )
    }
)